<template>
    <div>
        <!-- 查找区域 -->
        <div class="search">
            <el-input v-model="searchParams.key" style="width: 240px" placeholder="样本编码/冰箱/冻存架/冻存盒" clearable />
            <!-- <el-input v-model="searchParams.name" style="width: 200px" placeholder="样本状态" clearable /> -->
            <el-select v-model="searchParams.selectSampleState" placeholder="全部样本" size="enum" style="width: 240px">
                <el-option  v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <!-- <el-button @click="handleSearch">查询</el-button> -->
              <el-dropdown split-button  style="margin-right: 3px;" @click="search">
                                查询
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="advancedSearch">高级查询</el-dropdown-item>
                                        <el-dropdown-item @click="resetSearch">重置查询</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
            <el-button type="success" style=" margin-left: 10px;" @click="handleAdd">新增入库</el-button>
            <el-button type="success">出库</el-button>
            <el-button type="success">导出EXCEL</el-button>
        </div>
        <!-- 表格区域 -->
        <div class="form">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading" header-align="center">
                <el-table-column type="selection" width="55" header-align="center" />
                <el-table-column property="sampleCode" label="样本编码" width="120" header-align="center" />
                <el-table-column property="equipmentName" label="冰箱" width="120" header-align="center" />
                <el-table-column property="shelfCode" label="冻存架" width="240" header-align="center" />
                <el-table-column property="boxCode" label="冻存盒" header-align="center" />
                <el-table-column property="x" label="第X行" header-align="center" />
                <el-table-column property="y" label="第Y列" header-align="center" />
                <el-table-column property="receiveDate" label="采集日期" header-align="center" />
                <el-table-column property="sourceName" label="姓名" header-align="center" />
                <el-table-column property="sourceIdCard" label="身份证号" header-align="center" />
                <el-table-column property="sex" label="性别" header-align="center" />
                <el-table-column property="age" label="年龄" header-align="center" />
                <el-table-column property="telephone" label="手机号" header-align="center" />
                <el-table-column property="initCapacity" label="容量" header-align="center" />
                <el-table-column property="unit" label="单位" header-align="center" />
                <el-table-column property="validityDate" label="有效日期" header-align="center" />
                <el-table-column property="createOn" label="入库时间" header-align="center" />
                <el-table-column property="createBy" label="入库人" header-align="center" />
                <el-table-column property="outStockOn" label="出库时间" header-align="center" />
                <el-table-column property="outStockBy" label="出库人" header-align="center" />
                <el-table-column property="modifiedOn" label="修改时间" header-align="center" />
                <el-table-column property="remark" label="备注" header-align="center" />
                <el-table-column label="状态" width="70" fixed="right" header-align="center" property="state">
                    <template #default="scope">
                        <el-button v-if="scope.row.state == 1" size="small" link>入库</el-button>
                        <el-button v-if="scope.row.state == 2" size="small" link style="color: #00FF00;">出库</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right" header-align="center">
                    <template #default="scope">
                        <el-button size="small" type="success" @click="handleEdit(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                :page-size="pageSize" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>
        <!-- 新增/编辑窗口 -->
        <el-dialog v-model="dialogFormVisible" :title="formTitle" width="600">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="容器" prop="equipmentName">
                            <el-select v-model="form.equipmentName" placeholder="请选择样本类型" @click="equipment">
                                <el-option v-for="item in equipmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="冻存架" prop="shelfCode">
                            <el-select v-model="form.shelfCode" placeholder="请选择冻存架" @click="frozenshelf"
                                :disabled="!form.equipmentName">
                                <el-option v-for="item in shelfOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="冻存盒" prop="boxCode">
                            <el-select v-model="form.boxCode" placeholder="选择冻存盒" @click="forzenbox"
                                :disabled="!form.shelfCode">
                                <el-option v-for="item in boxOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="第X行" prop="x">
                            <el-input-number v-model="form.x" :min="1" :max="100" placeholder="请输入第X行" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="第Y列" prop="y">
                            <el-input-number v-model="form.y" :min="1" :max="100" placeholder="请输入第Y列" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="样本采集" prop="shelfCode">
                            <el-select v-model="form.sampleCode" placeholder="请选择样本采集" @click="samplesselect"
                                :disabled="!form.boxCode">
                                <el-option v-for="item in sampleOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="有效日期" prop="receiveDate">
                            <el-date-picker v-model="form.validityDate" type="date" placeholder="请选择样本采集日期" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="初始容量" prop="initCapacity">
                            <el-input-number v-model="form.initCapacity" :precision="2" :step="0.1" :min="1"
                                placeholder="请输入初始容量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位" prop="unit">
                            <el-input v-model="form.unit" placeholder="请输入单位" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirm" style="background-color: #17b3a3; color: white;">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 容器窗口 -->
        <el-dialog v-model="equipmentDialogVisible" title="选择容器" width="600">
            <el-input v-model="searchParams.key" style="width: 200px" placeholder="设备名称" clearable />
            <el-button @click="handleSearch">查询</el-button>
            <el-table :data="equipmentOptions" style="width: 100%">
                <el-table-column prop="name" label="设备名称" width="150" />
                <el-table-column prop="equipmentModelName" label="型号名称" width="120" />
                <el-table-column prop="equipmentGroupName" label="组名称" width="120" />
                <el-table-column prop="brand" label="品牌" width="120" />
                <el-table-column prop="modelVersion" label="型号" width="120" />
                <el-table-column prop="rowNums" label="层数" width="120" />
                <el-table-column prop="columnNums" label="列数" width="120" />
                <el-table-column prop="barcode" label="条形码" width="120" />
                <el-table-column prop="barcode2" label="二维码" width="120" />
                <el-table-column prop="hardcode" label="硬件编码" width="120" />
                <el-table-column prop="state" label="状态" width="120" />
                <el-table-column prop="produceDate" label="生产日期" width="120" />
                <el-table-column prop="useDate" label="使用日期" width="120" />
                <el-table-column prop="validityDate" label="有效日期" width="120" />
                <el-table-column prop="createOn" label="创建时间" width="120" />
                <el-table-column prop="modifiedOn" label="修改时间" width="120" />
                <el-table-column prop="remark" label="备注" width="120" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 冻存架窗口 -->
        <el-dialog v-model="shelfDialogVisible" title="选择冻存架" width="600">
            <el-input v-model="searchParams.key" style="width: 200px" placeholder="冻存架编码" clearable />
            <el-button @click="handleSearch">查询</el-button>
            <el-table :data="shelfOptions" style="width: 100%">
                <el-table-column prop="code" label="编码" width="150" />
                <el-table-column prop="shelfTypeName" label="规格" width="120" />
                <el-table-column prop="equipmentName" label="容器名称" width="120" />
                <el-table-column prop="rowNo" label="第X行" width="120" />
                <el-table-column prop="columnNo" label="第Y列" width="120" />
                <el-table-column prop="rowNums" label="行数" width="120" />
                <el-table-column prop="columnNums" label="列数" width="120" />
                <el-table-column prop="barcode" label="条形码" width="120" />
                <el-table-column prop="barcode2" label="条形码2" width="120" />
                <el-table-column prop="hardcode" label="硬件编码" width="120" />
                <el-table-column prop="modifiedOn" label="修改时间" width="120" />
                <el-table-column prop="remark" label="备注" width="120" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 冻存盒窗口 -->
        <el-dialog v-model="boxDialogVisible" title="选择冻存盒" width="600">
            <el-input v-model="searchParams.key" style="width: 200px" placeholder="冻存盒编码" clearable />
            <el-button @click="handleSearch">查询</el-button>
            <el-table :data="boxOptions" style="width: 100%">
                <el-table-column prop="shelfName" label="冻存架" width="150" />
                <el-table-column prop="rowNo" label="第X行" width="120" />
                <el-table-column prop="columnNo" label="第Y列" width="120" />
                <el-table-column prop="boxTypeName" label="规格" width="120" />
                <el-table-column prop="code" label="冻存盒编码" width="120" />
                <el-table-column prop="rowNums" label="行数" width="120" />
                <el-table-column prop="columNums" label="列数" width="120" />
                <el-table-column prop="equipmentName" label="冰箱" width="120" />
                <el-table-column prop="barcode" label="条形码" width="120" />
                <el-table-column prop="barcode2" label="二维码" width="120" />
                <el-table-column prop="hardwareOde" label="硬件编码" width="120" />
                <el-table-column prop="remark" label="备注" width="120" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 样本采集窗口 -->
        <el-dialog v-model="sampleDialogVisible" title="选择样本采集" width="600">
            <el-input v-model="searchParams.key" style="width: 200px" placeholder="样本编码" clearable />
            <el-button @click="handleSearch">查询</el-button>
            <el-table :data="sampleOptions" style="width: 100%">
                <el-table-column prop="sampleCode" label="样本编码" width="150" />
                <el-table-column prop="sourceName" label="姓名" width="120" />
                <el-table-column prop="collectAddressName" label="采集地点" width="120" />
                <el-table-column prop="collectDate" label="采集时间" width="120" />
                <el-table-column prop="sex" label="性别" width="120" />
                <el-table-column prop="idCard" label="身份证号" width="120" />
                <el-table-column prop="age" label="年龄" width="120" />
                <el-table-column prop="telephone" label="联系电话" width="120" />
                <el-table-column prop="createBy" label="录入人员" width="120" />
                <el-table-column prop="createOn" label="创建时间" width="120" />
                <el-table-column prop="sampleTypeName" label="样本类型" width="120" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClick3(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
// 导入API接口函数
import { list, add, userdel, detail, updata,selectSamples } from "@/api/biosample-detail"
import { getEquipment } from '@/api/equipment'
import { list as listShelf } from '@/api/forzenshelf'
import { list as listBox } from '@/api/forzenbox'
import { getSampesList as listSample } from '@/api/biosample-samples'
import { ref, reactive, onMounted } from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义TaskItem接口
interface TaskItem {
    id?: string,
    sampleCode: string,
    equipmentName: string
    shelfCode: string,
    boxCode: string,
    x: number,
    y: number,
    receiveDate: string,
    sourceName: string,
    sourceIdCard: string,
    sex: string,
    age: string,
    telephone: string,
    initCapacity: number,
    unit: string,
    validityDate: string,
    createOn: string,
    createBy: string,
    outStockOn: string,
    outStockBy: string,
    modifiedOn?: string,
    remark: string,
    key?: string | null // 用于重置查询
}

// 定义响应式引用和反应式对象
const ruleFormRef = ref<FormInstance | null>(null)
const form = reactive<TaskItem>({
    id: '',
    sampleCode: '',
    equipmentName: '',
    shelfCode: '',
    boxCode: '',
    x: 0,
    y: 0,
    receiveDate: '',
    sourceName: '',
    sourceIdCard: '',
    sex: '',
    age: '',
    telephone: '',
    initCapacity: 0,
    unit: '',
    validityDate: '',
    createOn: '',
    createBy: '',
    outStockOn: '',
    outStockBy: '',
    modifiedOn: '',
    remark: '',
    key: null // 用于重置查询
})

const query= reactive({
    key: null,
    t:new Date().getTime(),
    limit:10,
    page:1,   
})


// 定义表格数据、表单标题、对话框可见性控制、加载状态、选中行数据等响应式引用
const tableData = ref<TaskItem[]>([])
const formTitle = ref('')
const dialogFormVisible = ref(false)
const loading = ref(false)
const selectedRows = ref<TaskItem[]>([])
const currentId = ref<number | null>(null)

// 定义选择容器、冻存架、冻存盒、样本采集窗口的可见性控制
const equipmentDialogVisible = ref(false)
const shelfDialogVisible = ref(false)
const boxDialogVisible = ref(false)
const sampleDialogVisible = ref(false)

// 定义下拉选项数据
const equipmentOptions = ref([])
const shelfOptions = ref([])
const boxOptions = ref([])
const sampleOptions = ref([])

// 定义搜索参数
const searchParams = reactive({
    key: '',
    selectSampleState: '' 
})

const options=reactive([
    { value: '0', label: '全部样本' },
    { value: '1', label: '入库' },
    { value: '2', label: '出库' },
])

// 定义分页参数
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 定义表单验证规则
const rules = reactive<FormRules<TaskItem>>({
    sampleCode: [
        { required: true, message: '样本编码不能为空', trigger: 'blur' }
    ],
    equipmentName: [
        { required: true, message: '冰箱名称不能为空', trigger: 'blur' }
    ],
    shelfCode: [
        { required: true, message: '冻存架编码不能为空', trigger: 'blur' }
    ],
    boxCode: [
        { required: true, message: '冻存盒编码不能为空', trigger: 'blur' }
    ],
    x: [
        { required: true, message: '第X行不能为空', trigger: 'blur' },
        { type: 'number', min: 1, message: '第X行必须为大于0的数字', trigger: 'blur' }
    ],
    y: [
        { required: true, message: '第Y列不能为空', trigger: 'blur' },
        { type: 'number', min: 1, message: '第Y列必须为大于0的数字', trigger: 'blur' }
    ],
    sourceName: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    sourceIdCard: [
        { required: true, message: '身份证号不能为空', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '性别不能为空', trigger: 'blur' }
    ],
    age: [
        { required: true, message: '年龄不能为空', trigger: 'blur' },
        { pattern: /^\d+$/, message: '年龄必须为数字', trigger: 'blur' }
    ],
    telephone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    initCapacity: [
        { required: true, message: '初始容量不能为空', trigger: 'blur' },
    ],
    unit: [
        { required: true, message: '单位不能为空', trigger: 'blur' }
    ],
    receiveDate: [
        { required: true, message: '样本采集日期不能为空', trigger: 'blur' }
    ],
    validityDate: [
        { required: true, message: '有效日期不能为空', trigger: 'blur' }
    ]
})

// 定义分页参数对象
const pageParams = reactive({
    page: 1,
    rows: 10,
    name: ''
})

// 组件挂载后执行获取数据的操作
onMounted(() => {
    fetchData()
})

// 获取生物样本数据
function fetchData() {
    loading.value = true
    list({ ...pageParams, ...searchParams }).then(res => {
        tableData.value = res.page.list
        total.value = res.page.totalCount
        loading.value = false
    }).catch(() => {
        loading.value = false
    })
}

// 查询
function search() {
    form.key = 1
    fetchData()
}

//高级查询
function advancedSearch() {
    // reset()
    dialogFormVisible.value = true
}

// 重置查询
function resetSearch() {
    searchParams.selectSampleState = ''
    form.key = null
    fetchData()
}


// 处理查询操作，更新查询参数并重新获取数据
function handleSearch() {
    currentPage.value = 1
    pageParams.page = 1
    fetchData()
}

// 处理每页显示条数变化，更新分页参数并重新获取数据
function handleSizeChange(val: number) {
    pageSize.value = val
    pageParams.rows = val
    fetchData()
}

// 处理页码变化，更新分页参数并重新获取数据
function handlePageChange(val: number) {
    currentPage.value = val
    pageParams.page = val
    fetchData()
}

// 处理表格行选择变化，记录选中的行
function handleSelectionChange(rows: TaskItem[]) {
    selectedRows.value = rows
}

// 处理新增入库操作，重置表单并显示对话框
function handleAdd() {
    resetForm();
    formTitle.value = "新增";
    dialogFormVisible.value = true;
}

// 处理编辑操作，重置表单并显示对话框，同时获取当前选中行的数据
function handleEdit(row: TaskItem) {
    resetForm();
    formTitle.value = "编辑";
    dialogFormVisible.value = true;
    currentId.value = row.id || null;

    // 显示加载状态
    loading.value = true;

    // 获取详情数据并赋值给表单对象
    detail(row.id).then(res => {
        console.log(res, '数据');
        form.equipmentName = res.page.list.equipmentName
        form.shelfCode = res.page.list.shelfCode
        form.boxCode = res.page.list.boxCode
        form.remark = res.page.list.remark
        form.remark = res.page.list.remark
    })
        .catch(() => {
            ElMessage.error('获取详情失败');
            currentId.value = null;
        })
        .finally(() => {
            loading.value = false;
        });
}

// 重置表单数据
function resetForm() {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
        Object.assign(form, {
            id: '',
            sampleCode: '',
            equipmentName: '',
            shelfCode: '',
            boxCode: '',
            x: 0,
            y: 0,
            receiveDate: '',
            sourceName: '',
            sourceIdCard: '',
            sex: '',
            age: '',
            telephone: '',
            initCapacity: 0,
            unit: '',
            validityDate: '',
            createOn: '',
            createBy: '',
            outStockOn: '',
            outStockBy: '',
            modifiedOn: '',
            remark: '',
        });
    }
}


// 处理容器选择操作，获取容器选项并显示对话框
function equipment() {
    getEquipment().then(res => {
        equipmentOptions.value = res.page.list;
    }).catch(() => {
        ElMessage.error('获取设备失败');
    });
    equipmentDialogVisible.value = true;
}

// 处理冻存架选择操作，获取冻存架选项并显示对话框
function frozenshelf() {
    if (!form.equipmentName) {
        ElMessage.error('请先选择设备');
        return;
    }
    listShelf({ equipmentName: form.equipmentName }).then(res => {
        shelfOptions.value = res.page.list;
    }).catch(() => {
        ElMessage.error('获取冻存架失败');
    });
    shelfDialogVisible.value = true;
}

// 处理冻存盒选择操作，获取冻存盒选项并显示对话框
function forzenbox() {
    if (!form.shelfCode) {
        ElMessage.error('请先选择冻存架');
        return;
    }
    listBox({ shelfCode: form.shelfCode }).then(res => {
        boxOptions.value = res.page.list;
    }).catch(() => {
        ElMessage.error('获取冻存盒失败');
    });
    boxDialogVisible.value = true;
}

// 处理样本选择操作，获取样本选项并显示对话框
function samplesselect() {
   
    // 使用 form.boxCode 作为查询参数
    selectSamples(query).then(res => {
        console.log(res, '样本采集');
        sampleOptions.value = res.page.list;
        sampleDialogVisible.value = true;
    }).catch(() => {
        ElMessage.error('获取样本列表失败');
    });
}

// 处理点击选择操作，根据当前打开的对话框类型设置相应的表单字段值，并关闭对话框
function handleClick(row) {
    // 根据当前选择器设置值
    if (equipmentDialogVisible.value) {
        form.equipmentName = row.name;
        equipmentDialogVisible.value = false;
    } else if (shelfDialogVisible.value) {
        form.shelfCode = row.code;
        shelfDialogVisible.value = false;
    } else if (boxDialogVisible.value) {
        form.boxCode = row.code;
        boxDialogVisible.value = false;
    } 
    // else if (sampleDialogVisible.value) {
    //     // 样本采集选择器的具体数据设置
    //     form.sourceName = row.sourceName;
    //     form.sourceIdCard = row.idCard;
    //     form.sex = row.sex;
    //     form.age = row.age;
    //     form.telephone = row.telephone;
    //     form.receiveDate = row.collectDate;
    //     sampleDialogVisible.value = false;
    // }
}

// 样本采集
function handleClick3(row){
    form.sampleCode = row.sampleCode;
}

// 处理确认操作，根据表单标题（新增或编辑）调用相应的API函数，并处理返回结果
function handleConfirm() {
    if (formTitle.value === "新增") {
        add(form).then(() => {
            ElMessage.success('新增成功');
            fetchData();
            dialogFormVisible.value = false;
        }).catch(() => {
            ElMessage.error('新增失败');
        });
    } else if (formTitle.value === "编辑") {
        updata(currentId.value, form).then(() => {
            ElMessage.success('编辑成功');
            fetchData();
            dialogFormVisible.value = false;
        }).catch(() => {
            ElMessage.error('编辑失败');
        });
    }
}
</script>

<style scoped>
/*样式调整：为查找区域添加底部外边距*/
.search {
    margin-bottom: 20px;
}

/*样式调整：为分页区域添加顶部外边距和右浮动*/
.pagination {
    margin-top: 20px;
    float: right;
}
</style>
